﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RXY_Mall.Application.Base.Dto;
using RXY_Mall.Core;
using RXY_Mall.Domain;
using System.Data.Entity;

namespace RXY_Mall.Application.Base
{
    public class BaseService : RXY_MallAppServiceBase, IBaseService
    {
        #region 运费模板
        public async Task<Response<bool>> AddFreightTemplate(int managerId, FreightTemplateInput input)
        {
            var areas_count = input.areas == null ? 0 : input.areas.Count;
            var area_groups_count = input.area_groups == null ? 0 : input.area_groups.Count;
            StringBuilder errorList = new StringBuilder();
            if (string.IsNullOrEmpty(input.name))
            {
                errorList.Append("请输入模板名称；</br>");
            }
            if (areas_count == 0 && area_groups_count == 0)
            {
                errorList.Append("请设置配送区域；</br>");
            }
            var _has_name = db.gw_freight_templates.Any(i=>i.name==input.name);
            if (_has_name)
            {
                errorList.Append("模板名称已存在；</br>");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<bool>(errorList.ToString());
            }
            if (areas_count>0 && area_groups_count == 0)
            {
                input.chargetype = 1;
            }
            var gw_freight_template = new gw_freight_template {
                name = input.name,
                chargetype = (byte)input.chargetype,
                add_manager = managerId,
                add_time = DateTime.Now,
                is_delete = false,
                is_use = true,
                is_show=true,
                remark="",
            };
            var _template = db.gw_freight_templates.Add(gw_freight_template);
            await db.SaveChangesAsync();
            if (areas_count>0)
            {
                var _area_group= db.gw_freight_area_groups.Add(new gw_freight_area_group
                {
                    template_id = _template.id,
                    chargetype =1,
                    first_number = 1,
                    first_fee = 1,
                    add_number = 1,
                    add_fee = 1,
                });
                await db.SaveChangesAsync();
                foreach (var item in input.areas)
                {
                    db.gw_freight_distribution_areas.Add(new gw_freight_distribution_area
                    {
                        template_id = _template.id,
                        area_group_id = _area_group.id,
                        province = item.province,
                        province_code =item.province_code,
                    });
                }
                await db.SaveChangesAsync();
            }
            if (area_groups_count>0)
            {
                foreach (var group in input.area_groups)
                {
                    var _area_group = db.gw_freight_area_groups.Add(new gw_freight_area_group
                    {
                        template_id = _template.id,
                        chargetype = (byte)input.chargetype,
                        first_number = group.first_number,
                        first_fee = group.first_fee,
                        add_number = group.add_number,
                        add_fee = group.add_fee,
                    });
                    await db.SaveChangesAsync();
                    foreach (var area in group.areas)
                    {
                        db.gw_freight_distribution_areas.Add(new gw_freight_distribution_area
                        {
                            template_id = _template.id,
                            area_group_id = _area_group.id,
                            province = area.province,
                            province_code = area.province_code,
                        });
                    }
                    await db.SaveChangesAsync();
                }
            }
            return ReturnSuccess<bool>(true);
        }
        public bool SetTemplateIsShow(int manageId, int id, int isShow)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作运费模板{1}状态为{2}", manageId, id, isShow));
            var entity = db.gw_freight_templates.FirstOrDefault(i => i.id == id);
            entity.is_show = isShow==1?true:false;
            db.SaveChanges();
            return true;
        }
        public IList<FreightTemplateList> GetAllFreightTemplateByPage(int iDisplayStart, int iDisplayLength, string dateMin, string dateMax, string name, int type, int status, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            DateTime dtMin = DateTime.MinValue;
            DateTime dtMax = DateTime.MaxValue;
            var list = db.gw_freight_templates
                .Where(i =>! i.is_delete )
                .Select(item => new FreightTemplateList
                {
                    id = item.id,
                    name = item.name,
                    chargetype = item.chargetype,
                    is_use = item.is_use,
                    is_show = item.is_show,
                    add_time = item.add_time
                });
            if (type > -1)
            {
                list = list.Where(m => m.chargetype == type);
            }
            if (status > -1)
            {
                switch (status)
                {
                    case 0:
                        list = list.Where(m => !m.is_use);
                        break;
                    case 1:
                        list = list.Where(m => m.is_use);
                        break;
                }
                
            }
            if (!string.IsNullOrWhiteSpace(name))
            {
                list = list.Where(m => m.name.Contains(name));
            }
            if (!string.IsNullOrWhiteSpace(dateMin))
            {
                dtMin = DateTime.Parse(dateMin);
            }
            if (!string.IsNullOrWhiteSpace(dateMax))
            {
                dtMax = DateTime.Parse(dateMax).Date.AddDays(1); ;
            }
            list = list.Where(m => m.add_time >= dtMin && m.add_time <= dtMax);
            totalCount = list.Count();
            list = list.OrderByDescending(m => m.add_time).Skip(iDisplayStart).Take(iDisplayLength);
            return list.ToList();
        }

        public FreightTemplateInput GetFreightTemplateById(int id)
        {
            var template = db.gw_freight_templates.FirstOrDefault(i=>i.id==id);
            if (null!=template)
            {
                var freightTemplate= new FreightTemplateInput();
                freightTemplate.name = template.name;
                freightTemplate.chargetype = template.chargetype;
                freightTemplate.areas = db.gw_freight_distribution_areas.Include(i=>i.gw_freight_area_group).Where(i => i.template_id == template.id&&i.gw_freight_area_group.chargetype==1).Select(item=>new AreasDto {province_code=item.province_code,province=item.province }).ToList();
                freightTemplate.area_groups = db.gw_freight_area_groups.Include(i => i.gw_freight_distribution_area)
                    .Where(i => i.template_id == template.id && i.chargetype > 1)
                    .Select(m => new AreasGroupDto {
                        first_number=m.first_number,
                        first_fee=m.first_fee,
                        add_number=m.add_number,
                        add_fee=m.add_fee,
                        areas=m.gw_freight_distribution_area.Select(n=>new AreasDto { province_code=n.province_code,province=n.province}).ToList()
                    }).ToList();
                return freightTemplate;
            }
            else
            {
                return null;
            }
        }

        public List<FreightTemplateDto> GetFreightTemplate(int shopId)
        {
            var list = db.gw_freight_templates
                .Where(i => !i.is_delete&&i.is_use&&i.is_show)
                .Select(item => new FreightTemplateDto
                {
                    id = item.id,
                    name = item.name,
                    shop_id=item.shop_id,
                    chargetype = item.chargetype,
                }).ToList();
            if (shopId>0)
            {
                list.Where(i=>i.shop_id==shopId);
            }
            return list;
        }
        #endregion

        public List<gw_goods_category> GetCategoryListByPid(int parentId, int tid)
        {
            var list = db.gw_goods_categories.Where(i => i.parent_id == parentId && i.type == tid && i.status == 1).OrderBy(i => i.sort);
            return list.ToList();
        }
        public List<gw_base_area> GetPrivoceListByPid(int parentId)
        {
            return db.gw_base_areas.Where(i => i.parent_id == parentId).ToList();
        }

        public int SendOrderMsg()
        {
            int count = 0;
            DateTime cancelTime08 = DateTime.Parse("2018/10/08");
            //DateTime cancelTime28 = DateTime.Parse("2018/09/28");
            //var list28 = db.gw_orders.Include(i=>i.gw_order_goods).Where(i => i.cancel_time == cancelTime28&&i.order_no== "GFD180928071558426318").OrderBy(i=>i.id).Skip(0).Take(50).ToList();
            var list08 = db.gw_orders.Include(i => i.gw_order_goods).Where(i => i.cancel_time == cancelTime08 && i.order_no.Contains("GFD")).OrderBy(i => i.id).Skip(0).Take(50).ToList();
            //var list25buy = db.gw_orders.Include(i => i.gw_order_goods).Where(i => i.cancel_time == cancelTime25&&i.order_no.Contains("GOD")).OrderBy(i => i.id).Skip(0).Take(50).ToList();
            foreach (var item in list08)
            {
                //通知
                var message = new gw_message()
                {
                    user_id = item.user_id,
                    type = 1,
                    title = "合体免单失败通知",
                    summary = "真遗憾，因" + item.remark + "~",
                    content = "合体免单商品：" + item.gw_order_goods.FirstOrDefault().goods_name,
                    picture_url = item.gw_order_goods.FirstOrDefault().picture_url,
                    status = 1,
                    remark = "系统判定",
                    deleted = false,
                    add_time = DateTime.Now,
                };
                var model = db.gw_messages.Add(message);
                var gw_message_rule_order = new gw_message_rule_order()
                {
                    id = model.id,
                    order_no = item.order_no,
                    order_status = item.status
                };
                db.gw_message_rule_orders.Add(gw_message_rule_order);
                db.SaveChanges();
                count++;
            }
            //foreach (var item in list25buy)
            //{
            //    //通知
            //    var message = new gw_message()
            //    {
            //        user_id = item.user_id,
            //        type = 1,
            //        title = "订单取消通知",
            //        summary = "很抱歉，因" + item.remark,
            //        content = "订单商品：" + item.gw_order_goods.goods_name,
            //        picture_url = item.gw_order_goods.picture_url,
            //        status = 1,
            //        remark = "系统判定",
            //        deleted = false,
            //        add_time = (DateTime)item.cancel_time,
            //    };
            //    var model = db.gw_messages.Add(message);
            //    var gw_message_rule_order = new gw_message_rule_order()
            //    {
            //        id = model.id,
            //        order_no = item.order_no,
            //        order_status = item.order_status
            //    };
            //    db.gw_message_rule_orders.Add(gw_message_rule_order);
            //    db.SaveChanges();
            //    count++;
            //}

            return count;
        }
    }
}
